package com.tuanzi.loan.web.converter;

import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.core.util.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import java.util.Objects;

@FacesConverter("dictionaryConverter")
public class DictionaryConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		if (value != null && value.trim().length() > 0) {
			DictionaryService dictionaryService = SpringContextHolder.getBean(DictionaryService.class);
			return dictionaryService.findOne(value);
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (Objects.nonNull(value)) {
			if(StringUtils.isBlank(value.toString())){
				return null;
			}
			return ((Dictionary) value).getId();
		}
		return null;
	}
}
